const mqtt = require('mqtt');

// 连接到 MQTT over WebSocket 服务器
const client = mqtt.connect('ws://localhost:8883');

client.on('connect', () => {
    console.log('Connected to MQTT server');

    // 订阅一个主题
    client.subscribe('test/topic', (err) => {
        if (!err) {
            console.log('Subscribed to test/topic');
            // 发布一条消息
            client.publish('test/topic', 'Hello MQTT over WebSocket!');
        }
    });
});

// 接收消息
client.on('message', (topic, message) => {
    console.log(`Received message on ${topic}: ${message.toString()}`);
});

// 错误处理
client.on('error', (err) => {
    console.error('MQTT error:', err);
});